using Game.Common.Definition;
using Game.Framework;
using Unity.Collections;
using Unity.Entities;
using Unity.Jobs;
using Unity.Mathematics;
using Unity.Transforms;
using UnityEngine;

namespace Game.Core
{
    public unsafe partial struct SearchTargetJob : IJobEntity
    {
        [ReadOnly] public NativeArray<Entity> Entities;
        [ReadOnly] public ComponentLookup<Damageable> Damageables;
        [ReadOnly] public ComponentLookup<LocalTransform> Positions;

        void Execute(Entity entity, ref Attackable attackable)
        {
            // Debug.Log("SearchTargetJob");
            
            
            
            
            if (Entity.Null == attackable.Target)
            {
                var selfDamageable = Damageables[entity]; 
                var selfPos = Positions[entity];
                
                Entity target = Entity.Null;
                if (selfDamageable.Detail.CurHealthPoint > 0)
                {
                    // TODO: 设置为搜索半径
                    float nearest = float.MaxValue;
                   
                    float3 pos = default; 
                    for (int i = 0; i < Entities.Length; i++)
                    {
                        var temp = Entities[i];
                        if (temp == entity) continue;
                        var targetPos = Positions[temp];
                        var damageable = Damageables[temp];
                        var distance = math.distance(selfPos.Position, targetPos.Position);
                        if (distance < nearest && damageable.Detail.CurHealthPoint > 0)
                        {
                            nearest = distance;
                            target = temp;
                        }
                    }
                }
                attackable.Target = target;
            }
            else
            {
                // for (int i = 0; i < Entities.Length; i++)
                // {
                //     if (attackable.AttackTarget.Entity == Entities[i])
                //     {
                //         attackable.AttackTarget.Position = Positions[i].Value;
                //         break;
                //     }
                // }

                var damageable = Damageables[attackable.Target];
                if (damageable.Detail.CurHealthPoint <= 0)
                {
                    attackable.Target = Entity.Null;
                }
            }
        }
    }
}